<template>
  <div class="login">
    <div class="login-box">
      <img src="@/assets/common/login-logo.png" alt="" class="login">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item prop="mobile">
          <el-input
            v-model="form.mobile"
            prefix-icon="el-icon-user-solid"
            placeholder="请输入手机号"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            prefix-icon="el-icon-lock"
            show-password
            @keyup.enter.native="btnClick"
          />
          <!-- native能让组件使用原生方法 -->
        </el-form-item>
        <el-form-item>
          <el-button
            style="width: 100%; background: #407ffe"
            :loading="loading"
            @click="btnClick"
          >Log in</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        mobile: '13800000002', //	string	必须		手机号
        password: '123456' //	string	必须		密码
      },
      loading: false,
      rules: {
        mobile: [
          { required: true, message: '必填', trigger: 'change' },
          { min: 11, max: 11, trigger: 'change', message: '请输入手机号' },
          {
            validator: (rules, value, callback) => {
              const reg =
                /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
              if (reg.test(value)) {
                callback()
              } else {
                callback(new Error('请输入正确的手机号'))
              }
            },
            trigger: 'change'
          }
        ],
        password: [
          { required: true, message: '必填', trigger: 'change ' },
          { min: 5, max: 12, trigger: 'change', message: '请输入密码' }
        ]
      }
    }
  },
  methods: {
    btnClick() {
      this.$refs.form.validate(async(result) => {
        if (result) {
          this.loading = true
          try {
            await this.$store.dispatch('user/tologin', this.form)
            this.loading = false
            const redirect = this.$route.query.redirect || '/'
            this.$router.push(redirect)
          } catch {
            this.loading = false
          }
        } else {
          console.log('验证失败')
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100%;
  background: url('~@/assets/common/login.jpg');
  display: flex;
  justify-content: center;
  align-items: center;
  .login-box {
    text-align: center;
    .login {
      margin-bottom: 20px;
    }
    .el-button {
      width: 580px;
      border: none;
      color: #fff;
    }
  }
}
</style>
